package com.strongbj.iot.devices.dam.response.handle.v1;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.dam.message.DAMMessage;
import com.strongbj.iot.devices.dam.message.MQMessageOfDAM;
import com.strongbj.iot.devices.dam.response.entity.DestServerParamsResultEntity;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

public class GetDNSResultHandle extends DAMV1Handle {
	private static Logger logger = LogManager.getLogger(GetDNSResultHandle.class.getName());
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private static final String TOPIC="damCommandToService";
	private static final String ACTION_CODE = "resultDNSParams";
	private static final String DEV_TYPE="damDc";
	
	@Override
	protected boolean isHandleDAMMessage(DAMMessage t) {
		if(t.getCommand()==0x15){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, DAMMessage t) {
		MQMessageOfDAM msg = new MQMessageOfDAM();
		msg.setActioncode(ACTION_CODE);
		
		DestServerParamsResultEntity destServerParams=message2DestServerParamsResultEntity(t);
		msg.setAwsPostdata(destServerParams);
		msg.setDevType(DEV_TYPE);
		msg.setTimestamp(ByteUtil.bytesToLong(t.getSn()));
		String json = JSON.toJSONString(msg);
		logger.info("DAM设备 向MQ发送获取目标服务器参数的返回信息	 JSON={}",json);
		topicSender.send(TOPIC, json);
		return null;
	}
	
	private DestServerParamsResultEntity message2DestServerParamsResultEntity(DAMMessage t) {
		DestServerParamsResultEntity destServerParams=new DestServerParamsResultEntity();
		byte[] srcDatas = t.getDatas();
		String ip = Integer.toString(srcDatas[0])+"."+
				Integer.toString(srcDatas[1])+"."+
				Integer.toString(srcDatas[2])+"."+
				Integer.toString(srcDatas[3]);
		destServerParams.setDestIp(ip);
		
		return destServerParams;
	}
}

